﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ProtoImaginer.ProtoProject
{
    public partial class SearchByTag : PhoneApplicationPage
    {
        public SearchByTag()
        {
            InitializeComponent();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            DataContext = App.ViewModel;
            String parameterString = NavigationContext.QueryString["tag"];
            if (SearchTextbox.Text.Length > 0)
            {
                App.ViewModel.LoadSearchResultByTags(parameterString);
                ResultStat_TextBlock.Text = App.ViewModel.SearchResultStat().ToString() + " results are found";
                ResultStat_TextBlock.Visibility = Visibility.Visible;
            }
            else
            {
                ResultStat_TextBlock.Text = "Invalid input, please check your search keyword";
                ResultStat_TextBlock.Visibility = Visibility.Visible;
            }
        }

        private void SearchProject_Click(object sender, RoutedEventArgs e)
        {
            if (SearchTextbox.Text.Length > 0)
            {
                App.ViewModel.LoadSearchResultByTags(SearchTextbox.Text);
                ResultStat_TextBlock.Text = App.ViewModel.SearchResultStat().ToString() + " results are found";
                ResultStat_TextBlock.Visibility = Visibility.Visible;
            }
            else
            {
                ResultStat_TextBlock.Text = "Invalid input, please check your search keyword";
                ResultStat_TextBlock.Visibility = Visibility.Visible;
            }
        }

        private void Search_Text_Focus(object sender, RoutedEventArgs e)
        {
            SearchTextbox.SelectAll();
        }

        private void ProjectListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If selected index is -1 (no selection) do nothing
            if (ProjectListBox.SelectedIndex == -1)
                return;
            //NavigationService.Navigate(new Uri("/ProtoProject/ViewProject.xaml?selectedItem=" + ProjectListBox.SelectedIndex, UriKind.Relative));
            NavigationService.Navigate(new Uri("/ProtoProject/ViewProject.xaml?selectedItem=" + ProjectListBox.SelectedIndex, UriKind.Relative));
            ProjectListBox.SelectedIndex = -1;
        }

        private void SearchTextbox_TextChanged(object sender, TextChangedEventArgs e) { }

        private void OnKeyDownHandler(object sender, System.Windows.Input.KeyEventArgs e) { SearchProject_Click(sender, e); }
    }
}